# -*- coding:utf-8 -*-
from tornado import web, gen
import os

from appcommon.framework import APIRequestHandler
from appcommon import checktool
from common import decorator
from common import utiltool
import models as circlem
from user import models as userm
from common import timetool
import settings


class ReleaseCHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        content = self.get_argument('content', '')
        phone = self.get_argument('phone', '')
        longitude = self.get_argument('longitude', '')  # 经度
        latitude = self.get_argument('latitude', '')
        provice = self.get_argument('provice', '')
        city = self.get_argument('city', '')
        area = self.get_argument('area', '')
        belong_area = self.get_argument('belong_area', '')
        address = self.get_argument('address', '')
        couch = self.get_argument('couch', '0')

        is_silence = yield userm.check_phone_is_silence(phone)
        if is_silence == '1':
            res = dict(code="2", msg=u"您已经被管理员禁言")
        else:
            images = []
            if self.request.files:
                file_metas = self.request.files['file']
                for i, meta in enumerate(file_metas):
                    upload_path = settings.IMG_BASE_PATH + 'app/'
                    os.path.exists('upload_path')
                    filename = str(phone) + str(current_time) + '_' + str(i) + '.' + meta['filename'].split('.')[-1]
                    filepath = os.path.join(upload_path, filename)
                    with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                        up.write(meta['body'])
                    images.append(settings.IMG_BASE_URL + 'app/{}'.format(filename))
            yield circlem.save_circle_info_2_db(
                phone, content, longitude, latitude, provice, city, area, address, images, current_time, belong_area, couch)
            res = dict(code="0", msg="success")
        utiltool.response_write(self, res)


class DeleteCHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        c_id = self.get_argument('c_id', '')
        phone = self.get_argument('phone', '')
        info = yield circlem.get_circle_info_with_cid(c_id)
        if info:
            # img_list = info['images'].split()
            if phone == info['phone']:
                yield circlem.delete_circle_from_db(c_id)
                # yield circlem.delete_reply_from_db(c_id)
                # yield circlem.delete_zan_from_db(c_id)
                # reply_img_list = yield circlem.get_reply_images(c_id)
                # img_list += reply_img_list
                # circlem.remove_img_files(img_list)
                res = dict(code="0", msg=u"删除成功")
            else:
                res = {"code": 1, "msg": u"您无权删除"}
        else:
            res = dict(code="404", msg=u"话题已被删除")

        utiltool.response_write(self, res)


class ReplyHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        content = self.get_argument('content', '')
        c_id = self.get_argument('c_id', '')
        phone = self.get_argument('phone', '')
        to_phone = self.get_argument('to_phone', '')
        to_reply_id = self.get_argument('to_reply_id', '0')
        couch = self.get_argument('couch', '0')

        is_silence = yield userm.check_phone_is_silence(phone)
        if is_silence == '1':
            res = dict(code="2", msg=u"您已经被管理员禁言")
        else:
            circle_exists = yield circlem.check_circle_exists(c_id)
            if circle_exists:
                images = []
                if self.request.files:
                    file_metas = self.request.files['file']
                    for i, meta in enumerate(file_metas):
                        upload_path = settings.IMG_BASE_PATH + 'app/'
                        os.path.exists('upload_path')
                        filename = str(phone) + str(current_time) + '_' + str(i) + '.' + meta['filename'].split('.')[-1]
                        filepath = os.path.join(upload_path, filename)
                        with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                            up.write(meta['body'])
                        images.append(settings.IMG_BASE_URL + 'app/{}'.format(filename))
                if not to_phone:
                    tmp = yield circlem.get_phone_with_cid(c_id)
                    to_phone = tmp['phone']
                yield circlem.save_circle_reply_2_db(c_id, phone, content, images, current_time, to_reply_id, to_phone, couch)
                info_id = yield circlem.get_reply_id(c_id, phone, current_time)
                push_type = 0 if couch == '0' else 3
                yield circlem.add_psuh_task(push_type, info_id)
                res = dict(code="0", msg=u"发布成功")
            else:
                res = dict(code="404", msg=u"话题已被删除")
        utiltool.response_write(self, res)


class CircleListHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        c_id = self.get_argument('c_id', '')
        page_count = self.get_argument('page_count', '20')
        city = self.get_argument('city', 'nowhere')
        phone = self.get_argument('phone', '')
        couch = self.get_argument('couch', '0')
        info = yield circlem.get_circle_list_all(c_id, page_count, city, phone, couch)
        res = {"code": "0", "info": info}
        # 首次拉取， 带着指定信息和系统消息
        if not c_id:
            notice_info = yield circlem.get_notice_circle_list()
            circle_top_info = yield circlem.get_top_circle_list(phone, city, couch)
            res['notice_info'] = notice_info
            res['circle_top_info'] = circle_top_info
        utiltool.response_write(self, res)


class CircleDetailHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        c_id = self.get_argument('c_id', '')
        phone = self.get_argument('phone', '')
        info = yield circlem.get_circle_detail(c_id, phone)
        if info:
            res = {"code": "0", "info": info}
        else:
            res = dict(code="404", msg=u"话题已被删除")
        utiltool.response_write(self, res)


class ReplyListHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        c_id = self.get_argument('c_id', '')
        reply_id = self.get_argument('reply_id', '')
        page_count = self.get_argument('page_count', '20')
        circle_exists = yield circlem.check_circle_exists(c_id)
        if circle_exists:
            reply_list = yield circlem.get_reply_list(c_id, page_count, reply_id)
            for item in reply_list:
                user_info = yield circlem.get_user_info_with_phone(item['phone'])
                item['nick_name'] = user_info['nick_name']
                item['avatar'] = user_info['avatar']
                if item['to_reply_id']:
                    to_user_info = yield circlem.get_user_info_with_phone(item['to_phone'])
                    to_reply = yield circlem.get_reply_info(item['to_reply_id'])
                    item['to_nick_name'] = to_user_info['nick_name']
                    item['to_avatar'] = to_user_info['avatar']
                    item['content_reply'] = to_reply['content']
            reply_cnt = yield circlem.get_reply_cnt(c_id)
            res = {"code": "0", "info": reply_list, "reply_cnt": reply_cnt}
            # if not reply_id:
            #     total_cnt = yield circlem.get_reply_cnt(c_id)
            #     res['total_cnt'] = total_cnt
        else:
            res = dict(code="404", msg=u"话题已被删除")
        utiltool.response_write(self, res)


class ZanHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        current_time = timetool.get_timestamp()
        c_id = self.get_argument('c_id', '')
        phone = self.get_argument('phone', '')
        action = self.get_argument('action', '0')
        couch = self.get_argument('couch', '0')
        circle_exists = yield circlem.check_circle_exists(c_id)
        if circle_exists:
            if action != '0':
                yield circlem.cancel_zan(c_id, phone)
                res = {"code": "0", "msg": u"取消成功"}
            else:
                tmp = yield circlem.get_phone_with_cid(c_id)
                to_phone = tmp['phone']
                yield circlem.sava_zan_2_db(c_id, phone, to_phone, current_time, couch)
                info_id = yield circlem.get_zan_id(c_id, phone)
                push_type = 1 if couch == '0' else 4
                yield circlem.add_psuh_task(push_type, info_id)
                res = {"code": "0", "msg": u"点赞成功"}
        else:
            res = dict(code="404", msg=u"话题已被删除")
        utiltool.response_write(self, res)


class ZanListHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        c_id = self.get_argument('c_id', '')
        phone = self.get_argument('phone', '')
        zan_id = self.get_argument('zan_id', '')
        page_count = self.get_argument('page_count', '20')
        is_zan = yield circlem.check_zan(c_id, phone)
        zan_list = yield circlem.get_zan_list_with_c_id(c_id, zan_id, page_count)
        zan_cnt = yield circlem.get_zan_cnt(c_id)
        res = {"code": "0", "info": zan_list, "zan_cnt": zan_cnt, "is_zan": is_zan}
        utiltool.response_write(self, res)


class ZanMeHandler(APIRequestHandler):
    """收到的赞"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        zan_id = self.get_argument('zan_id', '')
        page_count = self.get_argument('page_count', '20')
        couch = self.get_argument('couch', '0')
        info = yield circlem.get_zan_me_list(phone, zan_id, page_count, couch)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class IReplyHandler(APIRequestHandler):
    """我回复的"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        reply_id = self.get_argument('reply_id', '')
        page_count = self.get_argument('page_count', '20')
        phone = self.get_argument('phone', '')
        couch = self.get_argument('couch', '0')
        info = yield circlem.get_i_reply_list(phone, reply_id, page_count, couch)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class ReplyMeHandler(APIRequestHandler):
    """回复我的"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        reply_id = self.get_argument('reply_id', '')
        page_count = self.get_argument('page_count', '20')
        couch = self.get_argument('couch', '0')
        info = yield circlem.get_reply_me_list(phone, reply_id, page_count, couch)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class MyCircleHandler(APIRequestHandler):
    """我的主题"""
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        phone = self.get_argument('phone', '')
        c_id = self.get_argument('c_id', '')
        page_count = self.get_argument('page_count', '20')
        couch = self.get_argument('couch', '0')
        info = yield circlem.get_my_circle_list(phone, c_id, page_count, couch)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)